<template>
  <div class="announcement-list">
    <el-card class="announcement-card">
      <template #header>
        <div class="card-header">
          <span>公告列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入公告标题"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">发布公告</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="announcementList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.isTop" type="danger" effect="dark" size="small">置顶</el-tag>
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getAnnouncementTypeTag(scope.row.type)">
              {{ formatAnnouncementType(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityTag(scope.row.priority)">
              {{ formatPriority(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column prop="publishAt" label="发布时间" width="180" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              size="small"
              type="success"
              @click="handlePublish(scope.row)"
              v-if="!scope.row.isPublished"
            >
              发布
            </el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑公告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="announcementFormRef"
        :model="announcementForm"
        :rules="announcementRules"
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="announcementForm.title" :maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="announcementForm.content" type="textarea" :rows="6" :maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="announcementForm.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="通知" value="NOTICE" />
            <el-option label="活动" value="EVENT" />
            <el-option label="维护" value="MAINTENANCE" />
            <el-option label="促销" value="PROMOTION" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="announcementForm.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option label="低" value="LOW" />
            <el-option label="普通" value="NORMAL" />
            <el-option label="高" value="HIGH" />
            <el-option label="紧急" value="URGENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标用户" prop="targetUsers">
          <el-select v-model="announcementForm.targetUsers" placeholder="请选择目标用户" style="width: 100%">
            <el-option label="所有人" value="ALL" />
            <el-option label="会员" value="MEMBERS" />
            <el-option label="教练" value="COACHES" />
            <el-option label="自定义" value="CUSTOM" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶" prop="isTop">
          <el-switch v-model="announcementForm.isTop" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-upload
            class="cover-uploader"
            action="/api/v1/files/upload"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
          >
            <img v-if="announcementForm.coverImage" :src="announcementForm.coverImage" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishAt">
          <el-date-picker
            v-model="announcementForm.publishAt"
            type="datetime"
            placeholder="请选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="过期时间" prop="expireAt">
          <el-date-picker
            v-model="announcementForm.expireAt"
            type="datetime"
            placeholder="请选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看公告详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="公告详情"
      width="800px"
    >
      <div class="announcement-detail">
        <h2>{{ currentAnnouncement.title }}</h2>
        <div class="meta">
          <span>类型：{{ formatAnnouncementType(currentAnnouncement.type) }}</span>
          <span>优先级：{{ formatPriority(currentAnnouncement.priority) }}</span>
          <span>发布时间：{{ currentAnnouncement.publishAt || '未发布' }}</span>
        </div>
        <div class="content" v-html="currentAnnouncement.content"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  Announcement,
  CreateAnnouncementRequest,
  UpdateAnnouncementRequest
} from '@/types/api/notification'
import { announcementApi } from '@/api/modules/notification'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const announcementList = ref<Announcement[]>([])

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const announcementFormRef = ref()
const currentAnnouncementId = ref(0)
const currentAnnouncement = ref<Announcement>({
  id: 0,
  title: '',
  content: '',
  type: 'NOTICE',
  priority: 'NORMAL',
  isTop: false,
  viewCount: 0,
  createdAt: ''
})

// 表单数据
const announcementForm = reactive({
  title: '',
  content: '',
  type: 'NOTICE',
  priority: 'NORMAL',
  targetUsers: 'ALL',
  coverImage: '',
  publishAt: '',
  expireAt: '',
  isTop: false
})

// 表单验证规则
const announcementRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 获取公告列表
const getAnnouncementList = async () => {
  try {
    loading.value = true
    const res = await announcementApi.getAnnouncementList({
      page: pagination.page,
      pageSize: pagination.pageSize
    })

    const data = res.data.data
    announcementList.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getAnnouncementList()
}

// 刷新列表
const refreshList = () => {
  getAnnouncementList()
}

// 添加公告
const handleAdd = () => {
  dialogTitle.value = '发布公告'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (row: Announcement) => {
  dialogTitle.value = '编辑公告'
  isEdit.value = true
  currentAnnouncementId.value = row.id
  Object.assign(announcementForm, row)
  dialogVisible.value = true
}

// 查看公告详情
const handleView = (row: Announcement) => {
  currentAnnouncement.value = row
  detailDialogVisible.value = true
}

// 发布公告
const handlePublish = async (row: Announcement) => {
  formUtils.handleDeleteConfirm('这条公告', async () => {
    await announcementApi.publishAnnouncement(row.id)
    refreshList()
  }, {
    title: '提示',
    successMessage: '发布成功',
    errorMessage: '发布失败'
  })
}

// 删除公告
const handleDelete = async (row: Announcement) => {
  formUtils.handleDeleteConfirm('这条公告', async () => {
    await announcementApi.deleteAnnouncement(row.id)
    refreshList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存公告
const handleSave = async () => {
  if (!announcementFormRef.value) return

  try {
    await announcementFormRef.value.validate()

    // 使用防重复提交保护
    const submitKey = isEdit.value ? `update_announcement_${currentAnnouncementId.value}` : 'create_announcement'

    await preventDuplicateSubmit(submitKey, async () => {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          // 编辑公告
          const updateData: UpdateAnnouncementRequest = {
            title: announcementForm.title,
            content: announcementForm.content,
            type: announcementForm.type as 'NOTICE' | 'EVENT' | 'MAINTENANCE' | 'PROMOTION',
            priority: announcementForm.priority as 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT',
            targetUsers: announcementForm.targetUsers as 'ALL' | 'MEMBERS' | 'COACHES' | 'CUSTOM',
            coverImage: announcementForm.coverImage,
            publishAt: announcementForm.publishAt,
            expireAt: announcementForm.expireAt,
            isTop: announcementForm.isTop
          }
          await announcementApi.updateAnnouncement(currentAnnouncementId.value, updateData)
        } else {
          // 创建公告
          const createData: CreateAnnouncementRequest = {
            title: announcementForm.title,
            content: announcementForm.content,
            type: announcementForm.type as 'NOTICE' | 'EVENT' | 'MAINTENANCE' | 'PROMOTION',
            priority: announcementForm.priority as 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT',
            targetUsers: announcementForm.targetUsers as 'ALL' | 'MEMBERS' | 'COACHES' | 'CUSTOM',
            coverImage: announcementForm.coverImage,
            publishAt: announcementForm.publishAt,
            expireAt: announcementForm.expireAt,
            isTop: announcementForm.isTop
          }
          await announcementApi.createAnnouncement(createData)
        }

        ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
        dialogVisible.value = false
        refreshList()
      } catch (error: any) {
        ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        saveLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(announcementForm, {
    title: '',
    content: '',
    type: 'NOTICE',
    priority: 'NORMAL',
    targetUsers: 'ALL',
    coverImage: '',
    publishAt: '',
    expireAt: '',
    isTop: false
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
  formUtils.resetForm(announcementFormRef.value, announcementForm)
}

// 上传封面图片相关方法
const handleCoverSuccess = (response: any, uploadFile: any) => {
  announcementForm.coverImage = response.data.file_url
  ElMessage.success('上传成功')
}

const beforeCoverUpload = (rawFile: any) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('封面图片只能是 JPG 或 PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('封面图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getAnnouncementList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getAnnouncementList()
}

// 格式化公告类型
const formatAnnouncementType = (type: string) => {
  const typeMap: Record<string, string> = {
    'NOTICE': '通知',
    'EVENT': '活动',
    'MAINTENANCE': '维护',
    'PROMOTION': '促销'
  }
  return typeMap[type] || type
}

// 获取公告类型标签
const getAnnouncementTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'NOTICE': '',
    'EVENT': 'success',
    'MAINTENANCE': 'warning',
    'PROMOTION': 'danger'
  }
  return tagMap[type] || ''
}

// 格式化优先级
const formatPriority = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'LOW': '低',
    'NORMAL': '普通',
    'HIGH': '高',
    'URGENT': '紧急'
  }
  return priorityMap[priority] || priority
}

// 获取优先级标签
const getPriorityTag = (priority: string) => {
  const tagMap: Record<string, string> = {
    'LOW': 'info',
    'NORMAL': '',
    'HIGH': 'warning',
    'URGENT': 'danger'
  }
  return tagMap[priority] || ''
}

// 生命周期
onMounted(() => {
  getAnnouncementList()
})
</script>

<style scoped>
.announcement-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.cover-uploader .cover {
  width: 178px;
  height: 178px;
  display: block;
}

.cover-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.cover-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.announcement-detail h2 {
  text-align: center;
  margin-bottom: 20px;
}

.announcement-detail .meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.announcement-detail .content {
  line-height: 1.8;
}
</style>
